
package com.amigo.online.consumer.merchant;

import java.util.Enumeration;

import javax.servlet.MultipartConfigElement;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.MultipartConfigFactory;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.Bean;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import feign.RequestInterceptor;


/**
<code>AmigoOnlineConsumerMerchantApplication</code>
<p>
	: 商家服务消费者
</p>
<p>
	@company Amigo
	@author LuChen
	@time 2018年12月14日 下午4:38:48
	@version 1.0 
	@lastUpdate 无
</p>
*/
@EnableDiscoveryClient
@EnableFeignClients
@SpringBootApplication
public class AmigoOnlineConsumerMerchantApplication {

	protected final Logger logger = LoggerFactory.getLogger(getClass());
    public static void main( String[] args ){
        SpringApplication.run(AmigoOnlineConsumerMerchantApplication.class, args);
    }
	
    
    @Bean
    public RequestInterceptor headerInterceptor() {
    	return template-> {
    		ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            HttpServletRequest request = attributes.getRequest();
            Enumeration<String> headerNames = request.getHeaderNames();
            if (headerNames != null) {
                while (headerNames.hasMoreElements()) {
                    String name = headerNames.nextElement();
                    String values = request.getHeader(name);
                    //过滤掉上传的头部信息  转换为json格式
                    //因为Feign调用provider不需要上传文件的头部信息   错误的头部会影响sleuth链路跟踪
                    if(StringUtils.contains(values, "multipart/form-data")) {
                    	values = "application/json";
                    }
                    logger.info("headers----"+name+":"+values);
                    template.header(name, values);
                }
            }
    	};
    }
	
    @Bean  
    public MultipartConfigElement multipartConfigElement() {
        MultipartConfigFactory factory = new MultipartConfigFactory();  
        //文件最大  
        factory.setMaxFileSize("102400KB"); //KB,MB  
        /// 设置总上传数据总大小  
        factory.setMaxRequestSize("1024000KB");         
        return factory.createMultipartConfig();  
    }  
}

